package cn.edu.klmy.dao.impl;

import cn.edu.klmy.dao.IAccountDao;
import com.googlecode.ehcache.annotations.*;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.jdbc.core.support.JdbcDaoSupport;
import org.springframework.stereotype.Repository;

import javax.annotation.Resource;
import javax.sql.DataSource;

@Repository
public class AccountDao extends JdbcDaoSupport implements IAccountDao {
    @Value("#{dataSourceProperties.User_DefaultPassword}")
    private String defaultPassword;

    private static final String ADD_ACCOUNT = "INSERT INTO USER(USER_ID_NO, USER_NAME, USER_PASSWORD, USER_TYPE) VALUES(?, ?, ?, ?)";

    @Override
    public void addAccount(String identityCardNumber, String username, int userType) {
        getJdbcTemplate().update(ADD_ACCOUNT, new Object[]{identityCardNumber, username, defaultPassword, userType});
    }

    private static final String REMOVE_ACCOUNT = "DELETE FROM USER WHERE USER_ID_NO = ?";

    @Override
    @TriggersRemove(cacheName = "userCache", when = When.AFTER_METHOD_INVOCATION,
            keyGenerator = @KeyGenerator(
                    name = "ListCacheKeyGenerator",
                    properties = @Property(name = "includeMethod", value = "false")
            )
    )
    public void removeAccount(String identityCardNumber) {
        getJdbcTemplate().update(REMOVE_ACCOUNT, new Object[]{identityCardNumber});
    }

    @Resource(name = "dataSource")
    public void setSuperDataSource(DataSource dataSource) {
        super.setDataSource(dataSource);
    }

    private static final String GET_ACCOUNT = "SELECT ID FROM USER WHERE USER_ID_NO = ?";
	@Override
    public int getAccountId(String identityCardNumber) {
		return getJdbcTemplate().queryForInt(GET_ACCOUNT, new Object[] { identityCardNumber });
	}

    private static final String CHANGE_ACCOUNT_USER_ID_NO = "UPDATE USER SET USER_ID_NO = ? WHERE USER_ID_NO = ?";

	@Override
    @TriggersRemove(cacheName = "userCache", when = When.AFTER_METHOD_INVOCATION,
            keyGenerator = @KeyGenerator(
                    name = "ListCacheKeyGenerator",
                    properties = @Property(name = "includeMethod", value = "false")
            )
    )
	public void changeAccountIdentityCardNumber(@PartialCacheKey String oldIdentityCardNumber,
			String newIdentityCardNumber) {
        getJdbcTemplate().update(CHANGE_ACCOUNT_USER_ID_NO, new Object[]{newIdentityCardNumber, oldIdentityCardNumber});
		
	}
}
